// 指纹管理模块
const FingerprintManager = {
    // 当前选中的员工
    selectedEmployee: null,
    
    // 当前选中的手指
    selectedFinger: null,
    
    // 采集器状态
    collectorStatus: 'disconnected',
    
    // 当前指纹数据
    currentFingerprint: null,
    
    // 初始化
    init() {
        this.initEventListeners();
        this.loadEmployees();
        this.checkCollectorStatus();
    },
    
    // 初始化事件监听器
    initEventListeners() {
        // 初始化采集器按钮
        document.getElementById('init-collector-btn').addEventListener('click', () => {
            this.initializeCollector();
        });
        
        // 员工搜索
        document.getElementById('employee-search').addEventListener('input', (e) => {
            this.searchEmployees(e.target.value);
        });
        
        // 手指选择
        document.querySelectorAll('.finger-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                this.selectFinger(e.target.dataset.finger);
            });
        });
        
        // 采集按钮
        document.getElementById('collect-btn').addEventListener('click', () => {
            this.startCollection();
        });
        
        // 重新采集按钮
        document.getElementById('retry-btn').addEventListener('click', () => {
            this.retryCollection();
        });
        
        // 保存指纹按钮
        document.getElementById('save-fingerprint-btn').addEventListener('click', () => {
            this.saveFingerprint();
        });
    },
    
    // 加载员工列表
    async loadEmployees() {
        try {
            const response = await AttendanceApp.api('/employee/list');
            const employees = response.data || [];
            
            this.renderEmployeeList(employees);
        } catch (error) {
            console.error('加载员工列表失败:', error);
            AttendanceApp.showNotification('加载员工列表失败', 'error');
        }
    },
    
    // 渲染员工列表
    renderEmployeeList(employees) {
        const container = document.getElementById('employee-list');
        container.innerHTML = '';
        
        if (employees.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">暂无员工数据</p>';
            return;
        }
        
        employees.forEach(employee => {
            const item = document.createElement('div');
            item.className = 'employee-item';
            item.dataset.employeeId = employee.id;
            
            item.innerHTML = `
                <h4>${employee.name}</h4>
                <p>工号: ${employee.employeeId}</p>
                <p>部门: ${employee.department || '未设置'}</p>
            `;
            
            item.addEventListener('click', () => {
                this.selectEmployee(employee);
            });
            
            container.appendChild(item);
        });
    },
    
    // 搜索员工
    searchEmployees(keyword) {
        const items = document.querySelectorAll('.employee-item');
        
        items.forEach(item => {
            const text = item.textContent.toLowerCase();
            const match = text.includes(keyword.toLowerCase());
            item.style.display = match ? 'block' : 'none';
        });
    },
    
    // 选择员工
    selectEmployee(employee) {
        // 更新选中状态
        document.querySelectorAll('.employee-item').forEach(item => {
            item.classList.remove('selected');
        });
        document.querySelector(`[data-employee-id="${employee.id}"]`).classList.add('selected');
        
        this.selectedEmployee = employee;
        
        // 加载该员工的指纹信息
        this.loadEmployeeFingerprints(employee.id);
        
        // 启用采集功能
        this.updateCollectionUI();
    },
    
    // 选择手指
    selectFinger(fingerIndex) {
        // 更新选中状态
        document.querySelectorAll('.finger-btn').forEach(btn => {
            btn.classList.remove('selected');
        });
        document.querySelector(`[data-finger="${fingerIndex}"]`).classList.add('selected');
        
        this.selectedFinger = fingerIndex;
        
        // 更新采集UI
        this.updateCollectionUI();
    },
    
    // 检查采集器状态
    async checkCollectorStatus() {
        try {
            const response = await AttendanceApp.api('/fingerprint/collector/status');
            const status = response.data;
            
            this.collectorStatus = status?.connected ? 'connected' : 'disconnected';
            this.updateCollectorStatusUI();
        } catch (error) {
            console.error('检查采集器状态失败:', error);
            this.collectorStatus = 'error';
            this.updateCollectorStatusUI();
        }
    },
    
    // 更新采集器状态UI
    updateCollectorStatusUI() {
        const statusElement = document.getElementById('collector-status');
        const statusText = statusElement.querySelector('span');
        
        statusElement.className = 'status-indicator';
        
        switch (this.collectorStatus) {
            case 'connected':
                statusElement.classList.add('connected');
                statusText.textContent = '设备已连接';
                break;
            case 'disconnected':
                statusText.textContent = '设备未连接';
                break;
            case 'error':
                statusElement.classList.add('error');
                statusText.textContent = '设备连接错误';
                break;
        }
        
        this.updateCollectionUI();
    },
    
    // 更新采集UI状态
    updateCollectionUI() {
        const collectBtn = document.getElementById('collect-btn');
        const canCollect = this.selectedEmployee && this.selectedFinger && this.collectorStatus === 'connected';
        
        collectBtn.disabled = !canCollect;
        
        if (canCollect) {
            document.querySelector('.fingerprint-image').classList.add('active');
        } else {
            document.querySelector('.fingerprint-image').classList.remove('active');
        }
    },
    
    // 初始化采集器
    async initializeCollector() {
        try {
            AttendanceApp.showLoading();
            
            const response = await AttendanceApp.api('/fingerprint/initialize', {
                method: 'POST'
            });
            
            if (response.success) {
                this.collectorStatus = 'connected';
                this.updateCollectorStatusUI();
                AttendanceApp.showNotification('采集器初始化成功', 'success');
            } else {
                throw new Error(response.message || '初始化失败');
            }
        } catch (error) {
            console.error('初始化采集器失败:', error);
            this.collectorStatus = 'error';
            this.updateCollectorStatusUI();
            AttendanceApp.showNotification('采集器初始化失败: ' + error.message, 'error');
        } finally {
            AttendanceApp.hideLoading();
        }
    },
    
    // 开始采集指纹
    async startCollection() {
        if (!this.selectedEmployee || !this.selectedFinger) {
            AttendanceApp.showNotification('请先选择员工和手指', 'warning');
            return;
        }
        
        try {
            // 更新UI状态
            document.getElementById('collect-btn').disabled = true;
            document.getElementById('retry-btn').disabled = true;
            document.getElementById('save-fingerprint-btn').disabled = true;
            
            // 显示采集中状态
            const fingerprintImage = document.querySelector('.fingerprint-image');
            fingerprintImage.innerHTML = `
                <i class="fas fa-spinner fa-spin"></i>
                <p>正在采集指纹...</p>
            `;
            
            // 调用采集API
            const response = await AttendanceApp.api(`/fingerprint/collect/${this.selectedEmployee.id}`, {
                method: 'POST',
                body: JSON.stringify({
                    fingerIndex: parseInt(this.selectedFinger)
                })
            });
            
            if (response.success) {
                this.currentFingerprint = response.data;
                this.showCollectionResult(response.data);
                AttendanceApp.showNotification('指纹采集成功', 'success');
            } else {
                throw new Error(response.message || '采集失败');
            }
        } catch (error) {
            console.error('指纹采集失败:', error);
            this.showCollectionError(error.message);
            AttendanceApp.showNotification('指纹采集失败: ' + error.message, 'error');
        } finally {
            // 恢复按钮状态
            document.getElementById('collect-btn').disabled = false;
            document.getElementById('retry-btn').disabled = false;
        }
    },
    
    // 显示采集结果
    showCollectionResult(data) {
        const fingerprintImage = document.querySelector('.fingerprint-image');
        fingerprintImage.innerHTML = `
            <i class="fas fa-fingerprint" style="color: #28a745;"></i>
            <p>指纹采集成功</p>
        `;
        
        // 更新质量指示器
        const quality = data.quality || 0;
        document.getElementById('quality-fill').style.width = quality + '%';
        document.getElementById('quality-text').textContent = quality + '%';
        
        // 启用保存按钮
        document.getElementById('save-fingerprint-btn').disabled = false;
    },
    
    // 显示采集错误
    showCollectionError(message) {
        const fingerprintImage = document.querySelector('.fingerprint-image');
        fingerprintImage.innerHTML = `
            <i class="fas fa-exclamation-triangle" style="color: #dc3545;"></i>
            <p>采集失败: ${message}</p>
        `;
        
        // 重置质量指示器
        document.getElementById('quality-fill').style.width = '0%';
        document.getElementById('quality-text').textContent = '0%';
        
        // 启用重试按钮
        document.getElementById('retry-btn').disabled = false;
    },
    
    // 重新采集
    retryCollection() {
        // 重置UI
        const fingerprintImage = document.querySelector('.fingerprint-image');
        fingerprintImage.innerHTML = `
            <i class="fas fa-fingerprint"></i>
            <p>请将手指放在采集器上</p>
        `;
        
        document.getElementById('quality-fill').style.width = '0%';
        document.getElementById('quality-text').textContent = '0%';
        
        // 重新开始采集
        this.startCollection();
    },
    
    // 保存指纹
    async saveFingerprint() {
        if (!this.currentFingerprint) {
            AttendanceApp.showNotification('没有可保存的指纹数据', 'warning');
            return;
        }
        
        try {
            AttendanceApp.showLoading();
            
            const response = await AttendanceApp.api('/fingerprint/save', {
                method: 'POST',
                body: JSON.stringify({
                    employeeId: this.selectedEmployee.id,
                    fingerIndex: parseInt(this.selectedFinger),
                    fingerprintData: this.currentFingerprint
                })
            });
            
            if (response.success) {
                AttendanceApp.showNotification('指纹保存成功', 'success');
                
                // 重新加载员工指纹列表
                this.loadEmployeeFingerprints(this.selectedEmployee.id);
                
                // 重置采集状态
                this.resetCollectionState();
            } else {
                throw new Error(response.message || '保存失败');
            }
        } catch (error) {
            console.error('保存指纹失败:', error);
            AttendanceApp.showNotification('保存指纹失败: ' + error.message, 'error');
        } finally {
            AttendanceApp.hideLoading();
        }
    },
    
    // 重置采集状态
    resetCollectionState() {
        this.currentFingerprint = null;
        
        // 重置UI
        const fingerprintImage = document.querySelector('.fingerprint-image');
        fingerprintImage.innerHTML = `
            <i class="fas fa-fingerprint"></i>
            <p>请将手指放在采集器上</p>
        `;
        
        document.getElementById('quality-fill').style.width = '0%';
        document.getElementById('quality-text').textContent = '0%';
        
        // 重置按钮状态
        document.getElementById('save-fingerprint-btn').disabled = true;
        document.getElementById('retry-btn').disabled = true;
        
        // 清除手指选择
        document.querySelectorAll('.finger-btn').forEach(btn => {
            btn.classList.remove('selected');
        });
        this.selectedFinger = null;
        
        this.updateCollectionUI();
    },
    
    // 加载员工指纹列表
    async loadEmployeeFingerprints(employeeId) {
        try {
            const response = await AttendanceApp.api(`/fingerprint/list/${employeeId}`, {
                method: 'POST'
            });
            
            const fingerprints = response.data || [];
            this.renderFingerprintList(fingerprints);
        } catch (error) {
            console.error('加载员工指纹失败:', error);
        }
    },
    
    // 渲染指纹列表
    renderFingerprintList(fingerprints) {
        const container = document.getElementById('collected-fingerprints');
        container.innerHTML = '';
        
        if (fingerprints.length === 0) {
            container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">该员工暂无指纹记录</p>';
            return;
        }
        
        fingerprints.forEach(fingerprint => {
            const card = document.createElement('div');
            card.className = 'fingerprint-card';
            
            const fingerName = this.getFingerName(fingerprint.fingerIndex);
            const quality = fingerprint.quality || 0;
            
            card.innerHTML = `
                <i class="fas fa-fingerprint"></i>
                <h5>${fingerName}</h5>
                <p>质量: ${quality}%</p>
                <p>采集时间: ${AttendanceApp.formatDate(fingerprint.collectionTime, 'MM-DD HH:mm')}</p>
                <div style="margin-top: 10px;">
                    <button class="btn btn-danger btn-sm" onclick="FingerprintManager.deleteFingerprint('${fingerprint.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            `;
            
            container.appendChild(card);
        });
    },
    
    // 获取手指名称
    getFingerName(fingerIndex) {
        const names = {
            1: '左拇指', 2: '左食指', 3: '左中指', 4: '左无名指', 5: '左小指',
            6: '右拇指', 7: '右食指', 8: '右中指', 9: '右无名指', 10: '右小指'
        };
        return names[fingerIndex] || `手指${fingerIndex}`;
    },
    
    // 删除指纹
    async deleteFingerprint(fingerprintId) {
        AttendanceApp.confirm('确定要删除这个指纹吗？', async () => {
            try {
                AttendanceApp.showLoading();
                
                const response = await AttendanceApp.api(`/fingerprint/delete/${fingerprintId}`, {
                    method: 'POST'
                });
                
                if (response.success) {
                    AttendanceApp.showNotification('指纹删除成功', 'success');
                    
                    // 重新加载指纹列表
                    if (this.selectedEmployee) {
                        this.loadEmployeeFingerprints(this.selectedEmployee.id);
                    }
                } else {
                    throw new Error(response.message || '删除失败');
                }
            } catch (error) {
                console.error('删除指纹失败:', error);
                AttendanceApp.showNotification('删除指纹失败: ' + error.message, 'error');
            } finally {
                AttendanceApp.hideLoading();
            }
        });
    }
};

